<?php

namespace addons\command\controller;

use Kreait\Firebase\Factory;
use Kreait\Firebase\Messaging\CloudMessage;
use Kreait\Firebase\Messaging\Notification;
use think\addons\Controller;

class Push extends Controller
{
    /*
     * php public/index.php /addons/command/push/index
     */
    public function index()
    {
        try {
            $factory = (new Factory)->withServiceAccount(APP_PATH . 'neon-shelter-382006-firebase-adminsdk-hevyo-b3e0422a6a.json');
            $messaging = $factory->createMessaging();
            $deviceToken = 'c6oeH4B6Ts-wt_-vxIT5_G:APA91bF-fJ9O9rqLZ_ujXtz53nuybAiKA9WaIuxqQB0CqYJ7Uv7x0kpPmw4Uqw4sbQyIq5DGrRpWW1JcFc55d4sJq_fzsX4xWAhxQ7bOyCMgRDiXw2bTYZmCyRgJBvt-oJrDlTJcapbX';
            $message = CloudMessage::withTarget('token', $deviceToken)
                ->withNotification(Notification::create('Title', 'Body'))
                ->withData(['key' => 'value']);
            $re =  $messaging->send($message);
            var_dump($re);
        }catch (\Exception $e){
            var_dump($e->getMessage());
        }
        echo '发送成功！';
        exit();
    }
    public function pushMsg()
    {
        $factory = (new Factory)->withServiceAccount(APP_PATH . 'neon-shelter-382006-firebase-adminsdk-hevyo-b3e0422a6a.json');
        $messaging = $factory->createMessaging();

        $deviceToken = '...';

        $message = CloudMessage::withTarget('token', $deviceToken)
            ->withNotification(Notification::create('Title', 'Body')) // optional
            ->withData(['key' => 'value']) // optional
        ;

        $message = CloudMessage::fromArray([
            'token' => $deviceToken,
            'notification' => [/* Notification data as array */], // optional
            'data' => [/* data array */], // optional
        ]);
        $messaging->send($message);

        $this->success('返回成功', []);
    }
}